<template>
    <div>
        <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
            <el-form :model="queryParams" ref="publicQueryForm" :inline="true" label-width="auto" label-position="left"
                :rules="shopProductRules">
                <el-form-item label="商品ID" prop="param.newIDs">
                    <el-input type="number" v-model.trim="queryParams.param.newIDs" placeholder="请输入" clearable
                        :min="1" />
                </el-form-item>
                <el-form-item label="商品名" prop="name">
                    <el-input style="width: 200px" v-model.trim="queryParams.param.name" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="来源货币" prop="currencyId">
                    <el-select style="width: 200px" v-model="queryParams.param.currencyId" placeholder="请选择" clearable>
                        <el-option v-for="dict in sys_currency_code" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="来源网站" prop="collectionSiteId">
                    <el-select style="width: 200px" v-model="queryParams.param.collectionSiteId" placeholder="请选择"
                        clearable @change="changeSite">
                        <el-option v-for="dict in host_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类" prop="categoryId">
                    <el-tree-select style="width: 200px" v-model="queryParams.param.categoryId" :data="categoryOptions"
                        :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
                        check-strictly clearable />
                </el-form-item>
                <el-form-item label="语言" prop="translatedLanguageId">
                    <el-select style="width: 200px" v-model="queryParams.param.translatedLanguageId" placeholder="请选择"
                        clearable>
                        <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description"
                            :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="更新时间" prop="time">
                    <el-date-picker v-model="queryParams.param.newTime" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </searchBox>

        <el-button type="primary" plain @click="productClaim(1, selectionId)"
            :disabled="!selectionId.length">快速认领</el-button>
        <el-button type="primary" plain @click="claimBatch = true">批量认领</el-button>


        <el-table :data="productList" @selection-change="handleSelectionChange" ref="productListRef"
            style="height: calc(100vh - 310px)" v-loading="loading">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" prop="id" width="100" />
            <el-table-column label="商品图" align="center" width="120">
                <template #default="scope">
                    <image-preview :src="scope.row.newImage" :width="75" :height="75" />
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" width="500">
                <template #default="scope">
                    <el-link :href="scope.row.rawUrl" target="_blank" :underline="false">{{
                        scope.row.name
                    }}</el-link>
                    <div style="display: flex;flex-direction: column;">
                        <div class="mb8">
                            <el-button type="primary" plain size="small">
                                {{ scope.row.languageName }}
                            </el-button>
                            <el-link :href="scope.row.collectionSiteUrl" target="_blank" :underline="false"
                                style="margin-left: 10px;">{{
                                    scope.row.collectionSiteName
                                }}</el-link>
                        </div>
                        <div>
                            <el-tag type="primary" v-if="scope.row.newRawCategories?.length">
                                <el-text style="max-width: 150px;" truncated> {{
                                    scope.row.newRawCategories[0]?.rawCategoryName
                                    }}</el-text>
                            </el-tag>

                            <el-tooltip effect="dark" placement="top-start">
                                <template #content>
                                    <el-space spacer=" " wrap>
                                        <div v-for="item in scope.row.newRawCategories" :key="item.id">
                                            <el-text style="color: #fff;" v-if="item.rawCategoryName">{{
                                                item.rawCategoryName }}</el-text>
                                        </div>
                                    </el-space>
                                </template>
                                <el-tag type="primary" style="margin-left: 10px;"
                                    v-if="scope.row.newRawCategories?.length > 1">More {{
                                        scope.row.newRawCategories?.length }}
                                </el-tag>
                            </el-tooltip>
                        </div>

                    </div>
                </template>
            </el-table-column>
            <el-table-column label="采集价格" width="200">
                <template #default="scope">
                    <el-tooltip placement="top">
                        <template #content>
                            <div>
                                {{ scope.row.collectionCurrencyName }}：{{
                                    scope.row.price }} {{ scope.row.collectionSymbol
                                }}
                                <br />
                                人民币：{{ scope.row.cnyprice }} ￥
                            </div>
                        </template>
                        <div>
                            <el-text>{{ scope.row.price }} {{ scope.row.collectionSymbol
                            }}</el-text>
                            <br />
                            <el-text type="info"> {{ scope.row.cnyprice }}
                                ￥</el-text>
                        </div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="已翻译语言" prop="translatedLanguageNameList" />
            <el-table-column label="审核人" prop="userName" />
            <el-table-column label="更新时间" prop="newEndDate" width="200px" align="center" />
            <el-table-column label="操作" align="center" width="150px" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" @click="publicIncident(scope.row, 0)">编辑</el-button>
                    <el-button link type="primary" @click="publicIncident(scope.row, 1)">认领</el-button>
                    <el-button link type="primary" @click="publicIncident(scope.row, 2)">货源</el-button>
                </template>
            </el-table-column>
        </el-table>

        <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum"
            @pagination="handlePageChange">
        </Pagination>

        <!-- <ProductEdit :publicFrom="publicItem" @handleEditClose="handleEditClose" :dialogEdit="dialogEdit"></ProductEdit> -->
        <PublicSource :PublicDialog="PublicDialog" :publicFrom="publicItem" @handlePublicSure="handlePublicSure"
            @handlePublicClose="handlePublicClose" :PublicType="true"></PublicSource>
        <el-dialog v-model="claimBatch" @close="handleClaimBatchClose" title="
批量认领" width="500px">
            <el-form :model="from" ref="queryBatchForm" :inline="true" label-width="auto" label-position="left"
                :rules="rules">
                <el-form-item label="来源网站" prop="collectionSiteId" required>
                    <el-select style="width: 300px" v-model="from.collectionSiteId" placeholder="请选择" clearable
                        @change="changeSite">
                        <el-option v-for="dict in host_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品分类" prop="rawCategoryId">
                    <el-tree-select style="width: 300px" v-model="from.rawCategoryId" :data="categoryOptions"
                        :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
                        check-strictly clearable />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleClaimBatchClose">取消</el-button>
                <el-button type="primary" @click="handleClaimBatchSure">确定
                </el-button>
            </template>
        </el-dialog>
        <PublicEdit :publicFrom="publicItem" :publicDialogEdit="publicDialogEdit"
            @handlePublicEditClose="handlePublicEditClose" :PublicType="true"></PublicEdit>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import PublicSource from "../product/publicPage/publicSource.vue";

import PublicEdit from "./publicEdit.vue";

const { proxy } = getCurrentInstance();
const sys_currency_code = ref([]); //来源货币列表数据
const sys_language_type = ref([]); //获取语言类别
const host_type = ref([]); //来源网站
const dialogEdit = ref(false)
const loading = ref(true)
const PublicDialog = ref(false)//默认货源弹出框是false
const claimBatch = ref(false)//默认货源弹出框是false
const publicDialogEdit = ref(false)//默认编辑弹出框是false

const total = ref(0); // 总条数
const productList = ref([]); // 产品中心表格数据
const selectionId = ref([])//勾选的id

// 类别管理下拉框
const categoryOptions = ref([]);
// 查询参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    param: {
        name: "", //产品名称
        currencyId: null, //来源货币
        collectionSiteId: null, //来源网站
        categoryId: null, //商品分类
        translatedLanguageId: null, //已翻译语言
        startTime: null, //开始时间
        endTime: null, //结束时间
        newTime: [],
        id: null,
        newIDs: null
    },
});
const from = ref({
    collectionSiteId: null,//来源网站
    rawCategoryId: null//公共采集类别ID
})
const publicItem = ref({}); //公共赋值对象

onMounted(() => {
    getList();
    getLanguage(); //获取下拉数据
});
/** 搜索按钮操作 */
const handleQuery = () => {
    proxy.$refs["publicQueryForm"].validate((valid) => {
        if (!valid) return
        queryParams.value.param.endTime = null
        queryParams.value.param.startTime = null
        queryParams.value.param.id = null
        if (queryParams.value.param.newTime?.length) {
            queryParams.value.param.startTime = proxy.convertTime(1, queryParams.value.param.newTime[0]);
            queryParams.value.param.endTime = proxy.convertTime(1, queryParams.value.param.newTime[1]);
        }
        if (queryParams.value.param.newIDs) {
            queryParams.value.param.id = Number(queryParams.value.param.newIDs)
        }
        getList();
    })

};
/** 重置按钮操作 */
const resetQuery = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        param: {
            name: "", //产品名称
            currencyId: null, //来源货币
            collectionSiteId: null, //来源网站
            categoryId: null, //商品分类
            translatedLanguageId: null, //已翻译语言
            startTime: null, //开始时间
            endTime: null, //结束时间
            newTime: [],
            id: null,
            newIDs: null
        },
    };
    getList();
};
/** 查询产品中心列表 */
const getList = () => {
    product.general
        .publicproductList({
            data: queryParams.value,
        })
        .then((res) => {
            total.value = res.total;
            loading.value = false
            if (res.data?.length) {
                res.data = res.data.map(code => {
                    return {
                        ...code,
                        newRawCategories: code.publicRawCategoryLineList || [],
                        newImage: handleImage(code),
                        newEndDate: proxy.DateTime(code.lastModified),

                    }
                })
            }
            productList.value = res.data;
            console.log(res.data);
        });
};
const publicIncident = (row, index) => {
    publicItem.value = row
    if (index === 1) {//认领
        let newIds = []
        newIds.push(row.id)
        productClaim(0, newIds)
    } else if (index === 2) {//货源
        PublicDialog.value = true
    } else {//编辑
        console.log('编辑');
        publicDialogEdit.value = true
    }
};
const productClaim = (index, ids) => {//认领商品
    let description = ''
    if (index) {
        description = '是否确认认领所有已勾选商品？'
    } else {
        description = '是否确认认领这件商品？'
    }
    proxy.$modal.confirm(description)
        .then(() => {
            product.personalproduct.personalproductAcquireproduct({ data: { ids: ids } }
            ).then((res) => {
                if (res.code == 200) {
                    selectionId.value = []
                    getList()
                    proxy.$modal.msgSuccess(res.message);
                }
            })
        })
}
const handleSelectionChange = (selection) => {// 多选框选中数据
    selectionId.value = selection.map((item) => item.id);
};
const changeSite = (e) => {
    queryParams.value.param.categoryId = null
    from.value.rawCategoryId = null
    categoryOptions.value = []
    productSortList(e)
}

const getLanguage = () => {
    // 来源货币
    product.currency.currencyList().then((res) => {
        if (res.data?.length) {
            res.data = res.data.map((code) => {
                return {
                    ...code,
                    label: code.description,
                    value: code.id,
                };
            });
        }
        sys_currency_code.value = res.data;
    });
    // 获取语言
    product.language.languageList().then((res) => {
        sys_language_type.value = res.data;
    });
    // 来源网站
    product.collectionsite
        .collectionsiteList({
            data: {
                pageNum: 1,
                pageSize: 999,
            },
        })
        .then((res) => {
            if (res.data?.length) {
                res.data = res.data.map((code) => {
                    return {
                        ...code,
                        label: code.name,
                        value: code.id,
                    };
                });
            }
            host_type.value = res.data;
        });


};
const productSortList = (e) => { // 采集商品分类
    product.rawcategory.rawcategoryList({
        data: {
            pageNum: 1,
            pageSize: 999,
            param: {
                languageId: 1,
                collectionSiteId: e
            },
        },
    })
        .then((response) => {
            categoryOptions.value = response.data;
        });
}
// 分页
const handlePageChange = (newPage) => {
    queryParams.value.pageNum = newPage.page;
    queryParams.value.pageSize = newPage.limit;
    getList();
};
const handleClaimBatchSure = () => {
    proxy.$refs["queryBatchForm"].validate((valid, fields) => {
        if (!valid) return
        product.personalproduct.personalproductAcquireproduct({ data: from.value }
        ).then((res) => {
            if (res.code == 200) {
                proxy.$modal.msgSuccess(res.message);
                handleClaimBatchClose()
            }
        });
    })
};



const handleImage = (row) => {
    var imageExtensionsRegex = /^https?:\/\//i;
    if (!imageExtensionsRegex.test(row.mainImage)) {
        return row.host
    } else {
        return row.mainImage
    }
}
const handleEditClose = () => {
    publicItem.value = {};
    dialogEdit.value = false
}
const handlePublicClose = () => {
    publicItem.value = {};
    PublicDialog.value = false
}
const handlePublicSure = () => {
    publicItem.value = {};
    PublicDialog.value = false
}
const handleClaimBatchClose = () => {
    claimBatch.value = false
    from.value.collectionSiteId = null
    from.value.rawCategoryId = null
    proxy.resetForm("queryBatchForm");
}
const rules = reactive({
    collectionSiteId: [{ required: true, message: '请选择', trigger: 'change' },]
})
const handlePublicEditClose = () => {
    publicItem.value = {};
    publicDialogEdit.value = false
}
const shopProductRules = reactive({
    'param.newIDs': [
        {
            pattern: /^[1-9]\d*$/,
            message: "请正确输入ID",
            trigger: "blur",
        },
    ],
})
</script>
<style lang="scss" scoped>
.Operation {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>